import { PrismaClient } from '@prisma/client'
import { rewardCalculationService } from '../services/rewardCalculationService'

interface CliOptions {
  userIds: number[] | null
  all: boolean
  startDate?: Date
  endDate?: Date
}

const prisma = new PrismaClient()

const parseArgs = (): CliOptions => {
  const options: CliOptions = {
    userIds: null,
    all: false
  }

  for (const arg of process.argv.slice(2)) {
    if (arg === '--all') {
      options.all = true
    } else if (arg.startsWith('--user=')) {
      const value = arg.replace('--user=', '').trim()
      const ids = value.split(',').map(item => Number(item.trim())).filter(id => !Number.isNaN(id))
      if (ids.length === 0) {
        throw new Error('无效的 --user 参数，至少需要一个有效的用户ID')
      }
      options.userIds = ids
    } else if (arg.startsWith('--start=')) {
      const value = arg.replace('--start=', '').trim()
      const parsed = new Date(value)
      if (Number.isNaN(parsed.getTime())) {
        throw new Error(`无效的开始日期: ${value}`)
      }
      options.startDate = parsed
    } else if (arg.startsWith('--end=')) {
      const value = arg.replace('--end=', '').trim()
      const parsed = new Date(value)
      if (Number.isNaN(parsed.getTime())) {
        throw new Error(`无效的结束日期: ${value}`)
      }
      options.endDate = parsed
    } else {
      throw new Error(`未知参数: ${arg}`)
    }
  }

  if (!options.all && (!options.userIds || options.userIds.length === 0)) {
    throw new Error('请使用 --user=<id> 或 --all 指定需要修复的用户')
  }

  return options
}

async function main(): Promise<void> {
  const options = parseArgs()
  const rangeInfo = []
  if (options.startDate) {
    rangeInfo.push(`开始 ${options.startDate.toISOString().slice(0, 10)}`)
  }
  if (options.endDate) {
    rangeInfo.push(`结束 ${options.endDate.toISOString().slice(0, 10)}`)
  }
  const rangeLabel = rangeInfo.length > 0 ? rangeInfo.join(' / ') : '自动（用户质押起始日至今）'

  let targetUserIds: number[]

  if (options.all) {
    const rows = await prisma.userStaking.findMany({
      select: { userId: true }
    })
    targetUserIds = rows.map(r => r.userId)
  } else {
    targetUserIds = options.userIds ?? []
  }

  console.log(`开始补发任务，目标用户数: ${targetUserIds.length}，区间: ${rangeLabel}`)

  let processedUsers = 0
  let totalInstallments = 0
  let totalRewardNear = 0

  for (const userId of targetUserIds) {
    try {
      const result = await rewardCalculationService.backfillUserRewards(userId, {
        startDate: options.startDate,
        endDate: options.endDate
      })

      if (result.processedInstallments > 0) {
        processedUsers += 1
        totalInstallments += result.processedInstallments
        totalRewardNear += result.totalRewardNear
        console.log(
          `✅ 用户 ${userId}: 补发 ${result.processedInstallments} 次 (共 ${result.totalRewardNear.toFixed(4)} NEAR)`
        )
      } else {
        console.log(
          `ℹ️ 用户 ${userId}: 无需补发`
        )
      }
    } catch (error) {
      console.error(`❌ 用户 ${userId} 补发失败:`, error)
    }
  }

  console.log(
    `补发任务完成：处理用户 ${processedUsers} 个，共补发 ${totalInstallments} 次，累计 ${totalRewardNear.toFixed(4)} NEAR`
  )
}

main()
  .catch((error) => {
    console.error('补发任务执行失败:', error)
    process.exitCode = 1
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
